#!/usr/bin/env python
#coding:utf-8

import sys
import re
import urllib2
import urllib
#import requests
import cookielib
import ConfigParser

reload(sys)
sys.setdefaultencoding("utf8")

class OJSubmit(object):
	def __init__(self, problemId, codeFile):
		config = ConfigParser.ConfigParser()
		try:
			config.read("ojsubmit.conf")
			self.loginUrl = config.get("oj", "login_url")
			self.submitUrl = config.get("oj", "submit_url")
			self.usernameParam = config.get("oj", "param_username")
			self.passwordParam = config.get("oj", "param_password")
			self.codeLanguageParam = config.get("oj", "param_language")
			self.problemIdParam = config.get("oj", "param_problemid")
			self.codeParam = config.get("oj", "param_code")
			self.username = config.get("oj", "login_username")
			self.password = config.get("oj", "login_password")
			self.codeLanguage = config.get("oj", "code_language")
		except Exception, msg:
			print "configure file not found or contains some error!->" + str(msg)
			sys.exit()
		self.problemId = problemId
		self.codeFile = codeFile
		
		f = open(codeFile)
		try:
			self.code = f.read()
		except Exception, e:
			print e
			f.close()
			sys.exit()
		
		self.logined = False
	def login(self):
		cj = cookielib.CookieJar()
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
		opener.addheaders = [('User-agent', 'Opera/9.23')]	
		urllib2.install_opener(opener)
		
		loginParams = {self.usernameParam : self.username, self.passwordParam : self.password}
		req = urllib2.Request(self.loginUrl, urllib.urlencode(loginParams))
		try:
			response = urllib2.urlopen(req)
			thePage = response.read()
			
			#fw = file("login.html", "w+")
			#fw.write(str(thePage))
			#fw.close()
		except Exception, msg:
			print "login error -> " + str(msg)
			sys.exit()
		
		self.logined = True		
	
	def submit(self):
		if self.logined == False:
			print "submission must occur after login"
			sys.exit()
		codeParams = {self.problemIdParam : self.problemId, self.codeLanguageParam : self.codeLanguage, self.codeParam : self.code}
		try:
			req = urllib2.Request(self.submitUrl, urllib.urlencode(codeParams))
			response = urllib2.urlopen(req)
			thePage = response.read()
			#fw = file("submit.html", "w+")
			#fw.write(str(thePage))
			#fw.close()
		except Exception, msg:
			print "submit error -> " + str(msg)
			sys.exit()


if __name__ == '__main__':
	problemId = ""
	codeFile = ""
	try:
		problemId = sys.argv[1]
		codeFile = sys.argv[2]
	except Exception, msg:
		print "Usage: ojsubmit {problem id} {code file name}"
		sys.exit()
	ojSubmit = OJSubmit(problemId, codeFile)
	ojSubmit.login()
	ojSubmit.submit()
